/*
 * Copyright (c) 2020-2022 Jinsp-tech. All rights reserved.
 */

package com.jinsp.networklibrary.filter;

import android.util.Log;

import com.jinsp.networklibrary.util.AESUtils;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;

/**
 * Created by luoshuai on 1/14/22
 * <p>
 * 数据加解密过滤器
 */
public class JsonCipherFilter extends IoFilterAdapter {

    private final String TAG = "JsonCipherFilter";

    @Override
    public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
        Log.d(TAG, "客户端收到服务端数据：" + message);
        if (message instanceof String) {
            String responseData = (String) message;
            String realResponseData = AESUtils.decryptString(responseData);
            Log.d(TAG, "解密服务端后的数据: " + realResponseData);
            super.messageReceived(nextFilter, session, realResponseData);
            return;
        }
        super.messageReceived(nextFilter, session, message);
    }

    @Override
    public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
        //数据经过AES加密
        String aesEncryptData = AESUtils.encryptString((String) writeRequest.getMessage());
        Log.d(TAG, "客户端加密后的数据: " + aesEncryptData);
        writeRequest.setMessage(aesEncryptData);
        super.filterWrite(nextFilter, session, writeRequest);
    }
}
